package com.systemsjr.mpf.account;

import java.text.ParseException;
import java.text.SimpleDateFormat;

import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

import com.systemsjr.mpf.IntentHandler;
import com.systemsjr.mpf.R;
import com.systemsjr.mpf.expense.ManageExpenseActivity;

public class AccountInstanceList extends ListActivity {

	private InstanceListAdapter adapter;
	private ListView listView;
	private Cursor c;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_account_instance_list);

		String[] from = { AccountInstance.INSTANCE, AccountInstance.BUDGET,
				AccountInstance.SPENT };
		AccountInstance accountInstance = new AccountInstance();
		c = getContentResolver().query(AccountInstance.CONTENT_URI, AccountInstance.PROJECTIONS,
				AccountInstance.ACTIVE_INSTANCES, null,
				AccountInstance.START_DATE + " DESC");

		/**
		 * This bundle will typically hold the search criteria in the form of
		 * parameters of an account instance
		 */
		Bundle bundle = getIntent().getExtras();
		if (bundle != null && bundle.size() > 0) {
			if (bundle.getString(AccountInstance.TABLE_NAME) != null) {
				accountInstance = (AccountInstance) bundle.get(AccountInstance.TABLE_NAME);
			}
			
			String selection = AccountInstance.INSTANCE
					+ " LIKE "
					+ (accountInstance.getInstance() == null
							|| accountInstance.getInstance().length() > 0 ? "'%'"
							: "'%" + accountInstance.getInstance() + "%'");

			selection = selection
					+ " AND "
					+ AccountInstance.ACCOUNT_FK
					+ (accountInstance.getAccount() == null ? " > 0" : " = "
							+ accountInstance.getAccount().getId());

			c = getContentResolver().query(AccountInstance.CONTENT_URI,
					AccountInstance.PROJECTIONS, selection, null,
					AccountInstance.START_DATE + " DESC");
		}
		
		startManagingCursor(c);
		int[] to = { R.id.list_instance, R.id.list_budget,
				R.id.list_used_amount };

		adapter = new InstanceListAdapter(this,
				R.layout.account_instance_list_entry, c, from, to, 0);
		listView = getListView();

		listView.setAdapter(adapter);
	
		Button instanceButton = (Button) findViewById(R.id.addInstanceButton);
		instanceButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(AccountInstanceList.this,
						ManageAccountInstanceActivity.class);
				startActivity(intent);
			}
		});

		Button expenseButton = (Button) findViewById(R.id.addExpenseButton);
		expenseButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				Intent intent = new Intent(AccountInstanceList.this,
						ManageExpenseActivity.class);
				startActivity(intent);

			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.account_instance_list, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		Intent intent = IntentHandler.handleOnOptionsItemSelected(this,
				item.getItemId());
		startActivityForResult(intent, 1);
		return super.onOptionsItemSelected(item);
	}

	@Override
	protected void onResume() {
		super.onResume();
		// c.requery();
		adapter.notifyDataSetChanged();
		listView.invalidateViews();
	}
	
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		Intent intent = new Intent(AccountInstanceList.this,
				ViewAccountInstanceActivity.class);

		if (adapter != null) {
			Cursor c = (Cursor) adapter.getItem(position);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

			AccountInstance instance = new AccountInstance();
			instance.setId(c.getLong(c.getColumnIndex(AccountInstance.ID)));
			instance.setSpent(c.getDouble(c
					.getColumnIndex(AccountInstance.SPENT)));
			instance.setBudget(c.getDouble(c
					.getColumnIndex(AccountInstance.BUDGET)));
			instance.setInstance(c.getString(c
					.getColumnIndex(AccountInstance.INSTANCE)));
			try {
				instance.setStartDate(sdf.parse(c.getString(c
						.getColumnIndex(AccountInstance.START_DATE))));

				if (c.getString(c.getColumnIndex(AccountInstance.CLOSE_DATE)) != null) {
					instance.setCloseDate(sdf.parse(c.getString(c
							.getColumnIndex(AccountInstance.CLOSE_DATE))));
				}
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			Cursor c1 = getContentResolver()
					.query(Account.CONTENT_URI,
							Account.PROJECTIONS,
							Account.ID + " = "
									+ c.getLong(c
											.getColumnIndex(AccountInstance.ACCOUNT_FK)),
							null, null);
			Account a = new Account();
			if (c1.moveToFirst()) {
				a.setId(c1.getLong(c1.getColumnIndex(Account.ID)));
				a.setCode(c1.getString(c1.getColumnIndex(Account.CODE)));
				a.setAccount(c1.getString(c1.getColumnIndex(Account.ACCOUNT)));
			} else {
				// TODO: error message
			}
			c1.close();

			instance.setAccount(a);
			intent.putExtra(AccountInstance.TABLE_NAME, instance);
		}
		startActivityForResult(intent, 1);
	}
}
